// 创建用户相关的小仓库
import { defineStore } from "pinia";
import { loginForm } from "@/api/user/type";
import { reqLogin, reqLogout } from "@/api/user";
import { GET_TOKEN, SET_TOKEN, CLEAR_TOKEN } from "@/utils/catch";
import { UserState } from "./types/type";

let useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
    };
  },
  actions: {
    saveToken(token: string) {
      this.token = token;
      SET_TOKEN(token);
    },
    async userLogin(data: loginForm) {
      let result = await reqLogin(data);
      if (result.code === 200) {
        this.token = result.data.token;
      } else {
        console.log("请求失败");
      }
    },
    userLogout() {
      return new Promise<void>((resolve, reject) => {
        reqLogout()
          .then(() => {
            CLEAR_TOKEN();
            this.token = null;
            setTimeout(() => {
              resolve();
            }, 500);
          })
          .catch((err) => reject(err));
      });
    },
  },
  getters: {},
});

export default useUserStore;
